/**
* 团队管理
*/
import React, { Component } from 'react';
import { View, StyleSheet, Text, Image, TouchableOpacity, FlatList, Alert, DeviceEventEmitter, StatusBar } from "react-native";
import { connect } from 'react-redux';
import { create_service } from '../../redux/index.js';
import { Contract } from '../../service/index.js';
import { Colors, Dimens, ImageRes } from '../../utils/Assets';
import { ProgressView } from '../custom/index'
import { Actions } from 'react-native-router-flux';
import ScrollableTabView from 'react-native-scrollable-tab-view'
import { getStore } from '../../redux/index.js';
import {toast} from '../../utils/Toast';

class BankCardListView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            searchMonth: "",
            searchTime: '',
            currentIndex: 0,
            tabbarName: ['信用卡', '储蓄卡'],
            rightTitle: '管理',
            refreshing: false,
            delete: false,
            rightTitle: '管理',
        }
        this.userInfo = getStore().getState().auth.userInfo
    }

    componentDidMount() {
        this.listener = DeviceEventEmitter.addListener('ChangeIndex', (value) => {
            this.setState({ currentIndex: value.index })
        })
    }
    componentWillUnmount() {
        this.listener && this.listener.remove()
    }

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.nav}>
                    <TouchableOpacity style={{ justifyContent: 'center', flex: 1 }} activeOpacity={0.8} onPress={() => {
                        Actions.pop()
                    }}>
                        <Image source={ImageRes.icon_back_white} style={{ width: 26, height: 26, marginLeft: 10 }}></Image>
                    </TouchableOpacity>
                    <View style={{ flex: 1, justifyContent: 'center' }}>
                        <Text style={{ color: '#fff', fontSize: 18, alignSelf: 'center', fontWeight: 'bold', alignSelf: 'center' }}>我的银行卡</Text>
                    </View>
                    <View style={{ flex: 1, justifyContent: 'flex-end', flexDirection: 'row' }}>
                        {/* {this.state.rightTitle == '完成' && <TouchableOpacity style={{ justifyContent: 'center', marginRight: 15 }} onPress={() => {
                            this.deleteClick()
                        }}>
                            <Text style={{ fontSize: 16, color: '#FC2222', alignSelf: 'center' }}>{'删除'}</Text>
                        </TouchableOpacity>} */}
                        <TouchableOpacity style={{ justifyContent: 'center', marginRight: 15 }} onPress={() => {
                            this.setState({ rightTitle: this.state.rightTitle == '管理' ? '完成' : '管理', delete: !this.state.delete })
                        }}>
                            <Text style={{ fontSize: 16, color: '#fff', alignSelf: 'center' }}>{this.state.rightTitle}</Text>
                        </TouchableOpacity>
                    </View>
                </View>
                <ScrollableTabView
                    locked={true}
                    renderTabBar={() => <TabBar />}>
                    {
                        this.state.tabbarName.map((item, index) => {
                            return (
                                <SubView key={index} tabLabel={item} index={index} dispatch={this.props.dispatch} userInfo={this.userInfo} users_id={this.props.users_id} delete={this.state.delete} />
                            )
                        })
                    }
                </ScrollableTabView>
            </View>
        )
    }
}
class SubView extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            refreshing: false,
            rightTitle: '管理',
            bank_list: []
        }
        this.pageSize = 10
        this.page = 1
        this.userInfo = getStore().getState().auth.userInfo
        this.selBank = null
    }

    componentDidMount() {
        this.getDataList(true)
    }

    deleteClick() {
        if (this.selBank) {
            Alert.alert(
                '提醒',
                `确认删除  ${this.selBank.name}(${this.selBank.full_card_number.substring(this.selBank.full_card_number.length - 4)})`,
                [
                    { text: '取消', onPress: () => { } },
                    {
                        text: '确定', onPress: () => {
                            this.setState({ delete: !this.state.delete, rightTitle: '管理' }, () => {
                                this.deleteItem()
                            })
                        }
                    },
                ],
                { cancelable: false }
            )
        } else {
            toast('请选要删除的银行卡')
            return
        }
    }
    
    deleteItem() {
        this.setState({ loading: true })
        this.props.dispatch(create_service(Contract.POST_USER_BANKCARD_DELETE, { id: this.selBank.id, token: this.userInfo.token })).then((res) => {
            if (res) {
                this.page = 1
                this.getDataList(true)
            }
            this.setState({ loading: false })
        })
    }
    getDataList(refresh) {
        if (refresh) {
            this.setState({ refreshing: true })
        } else {
            this.setState({ loading: true })
        }

        let type = '02'
        if(this.props.index == 1){
            type = '00'
        }

        this.props.dispatch(create_service(Contract.POST_USER_BANK_CARD_LIST, { page: this.page, pageSize: this.pageSize, type: type, token: this.userInfo.token })).then((res) => {
            if (res) {
                if (refresh) {
                    this.setState({ bank_list: res.list, pagination: res.pagination, loading: false, refreshing: false })
                } else {
                    this.setState({ bank_list: this.state.bank_list.concat(res.list), pagination: res.pagination, loading: false, refreshing: false })
                }
            } else {
                this.setState({ loading: false, refreshing: false })
            }
        })
    }
    onEndReached() {
        if (this.state.bank_list.length != 0 && this.state.bank_list.length != this.state.pagination.total) {
            this.page += 1
            this.getDataList(false)
        }
    }
    componentWillUnmount() {
    }
    renderItem({ item, index }) {
        return (
            <View style={{ flexDirection: 'column', marginHorizontal: 15, alignItems:'center', marginTop: 15, padding: 15, backgroundColor: item.color, borderRadius: 8 }}>
                <View style={{ flex: 1 }}>
                    <View style={{ flexDirection: 'row' }}>
                        <Image style={{ width: 40, height: 40, borderRadius: 40 }} source={{ uri: item.bank_logo }}></Image>
                        <View style={{ justifyContent: 'center', marginLeft: 15 }}>
                            <Text style={{ fontSize: 16, color: "#ffffff" }}>{item.name}</Text>
                            <Text style={{ fontSize: 12, color: "#ffffff", marginTop: 5 }}>{item.type == '00' ? '储蓄卡' : '信用卡'}</Text>
                        </View>
                    </View>
                    <View style={styles.cardNumber}>
                        <Text style={styles.cardNumberItem}>****</Text>
                        <Text style={styles.cardNumberItem}>****</Text>
                        <Text style={styles.cardNumberItem}>****</Text>
                        <Text style={styles.cardNumberItem}>{item.card_number}</Text>
                        {/* {"****  ****  ****  " + item.card_number} */}
                    </View>
                </View>
                {this.props.delete && 
                    <View style={{width: Dimens.DeviceWidth - 30, alignItems: 'center', flexDirection:'row',marginTop:20}}>
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {
                            Actions.BankCardInfoView({info:item, reloadList: () => {
                                this.page = 1
                                this.getDataList(true)
                            }})
                            this.setState({ loading: false })
                        }}>
                            <View style={{width: (Dimens.DeviceWidth - 30)/2,alignItems:'center',  paddingTop:10, paddingBottom:10}}>
                                <Text style={{color:'#fff'}}>编辑</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {
                            this.selBank = item
                            this.deleteClick()
                            this.setState({ loading: false })
                        }}>
                            <View style={{width: (Dimens.DeviceWidth - 30)/2,alignItems:'center',  paddingTop:10, paddingBottom:10}}>
                                <Text style={{color:'#fff'}}>删除</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                }
            </View>
        )
    }
    renderFootView() {
        return (
            <TouchableOpacity style={{ backgroundColor: '#ffffff', padding: 15, borderRadius: 8, width: Dimens.DeviceWidth - 30, flexDirection: 'row', marginLeft: 15, marginVertical: 20 }} onPress={() => {
                {
                    this.props.index === 1?
                        Actions.personalAddBankView({
                            reloadList: () => {
                                this.page = 1
                                this.getDataList(true)
                            }
                        })
                    :
                        Actions.AddCreditCardView({
                            reloadList: () => {
                                this.page = 1
                                this.getDataList(true)
                            }
                        })
                }
                
            }} activeOpacity={0.8} >
                <Image source={ImageRes.personal_plus} style={{ width: 18, height: 18, alignSelf: 'center' }}></Image>
                <Text style={{ fontSize: 16, color: "#333333", alignSelf: 'center', marginLeft: 15 }}>
                    {
                        this.props.index === 1?
                            "添加银行卡"
                            :
                            "添加储蓄卡"
                    }
                </Text>
            </TouchableOpacity>
        )
    }
    render() {
        return (
            <View style={styles.container}>
                <View style={{ flex: 1 }}>
                    <FlatList
                        ref={(list) => (this.flatList = list)}
                        keyExtractor={(item, index) => index.toString()}
                        data={this.state.bank_list}
                        ItemSeparatorComponent={() => <View style={{ backgroundColor: Colors.bg_color, height: 1 }} />}
                        showsVerticalScrollIndicator={false}
                        renderItem={this.renderItem.bind(this)}
                        refreshing={this.state.refreshing}
                        onEndReachedThreshold={0.1}
                        ListFooterComponent={this.renderFootView.bind(this)}
                        onRefresh={() => {
                            this.page = 1
                            this.getDataList(true)
                        }}
                        onEndReached={() => {
                            this.onEndReached();
                        }}
                    />
                </View>
                <ProgressView show={this.state.loading} />
            </View>
        )
    }
}
const TabBar = (props) => {
    let { tabs, activeTab, goToPage } = props;
    return (
        <View style={{ backgroundColor: Colors.white_color, width: Dimens.DeviceWidth, height: 50, flexDirection: 'row' }}>
            {tabs.map((tab, i) => (
                <TouchableOpacity onPress={() => {
                    goToPage(i)
                    DeviceEventEmitter.emit('ChangeIndex', { index: i })
                }} activeOpacity={0.8} key={i} style={{ flex: 1, height: 50, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 15, backgroundColor: Colors.white_color }}>
                    <View style={{ flexDirection: 'row' }}>
                        <Text style={{ color: (activeTab == i ? '#378EFB' : "#333333"), fontSize: 14, alignSelf: 'center' }}>{tab}</Text>
                    </View>
                    <View style={{ width: 100, height: 3, backgroundColor: (activeTab == i ? "#378EFB" : 'transparent'), position: 'absolute', bottom: 0, alignSelf: 'center' }} />
                </TouchableOpacity>
            ))}
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Colors.bg_color,
    },
    nav: {
        height: Dimens.isAndroid ? 64 : (Dimens.isIPhoneX ? 88 : 64),
        backgroundColor: 'rgba(55, 142, 251, 1)',
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingTop: Dimens.isAndroid ? StatusBar.currentHeight + 10 : (Dimens.isIPhoneX ? 44 : 20)
    },
    cardNumber:{ 
        fontSize: 18, 
        width:Dimens.DeviceWidth - 150, 
        color: "#ffffff",
        marginTop: 10, 
        marginLeft: 55, 
        fontWeight: 'bold', 
        display:'flex', 
        alignItems:'center',
        justifyContent:'space-between' ,
        flexDirection:'row',
        lineHeight:18
    },
    cardNumberItem:{
        fontSize: 18, 
        color: "#ffffff",
        fontWeight: 'bold', 
    }
});
const ExportView = connect()(BankCardListView);
module.exports.BankCardListView = ExportView
